package com.ruoyi.whzj.controller;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.EmptyUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sql.SqlUtil;
import com.ruoyi.whzj.domain.*;
import com.ruoyi.whzj.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 活动Controller
 * 
 * @author ruoyi
 * @date 2020-09-02
 */
@Controller
@RequestMapping("/whzj/report")
public class WhReportController extends BaseController
{
    private String prefix = "whzj/report";

    @Autowired
    private IWhTaskService whTaskService;
    @Autowired
    private IWhUserService whUserService;
    @Autowired
    private IWhBalancerecordService whBalancerecordService;
    @Autowired
    private IWhUserwithdrawService whUserwithdrawService;
    @Autowired
    private IWhPayrecordService whPayrecordService;

    @RequiresPermissions("whzj:report:view")
    @GetMapping()
    public String activity()
    {
        return prefix + "/report";
    }

    /**
     * 查询列表
     */
    @RequiresPermissions("whzj:report:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(String yearSearch, String monthSearch) throws ParseException {
        //startPage();
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
        List<WhReport> list = new ArrayList<>();
        //获取系统日期
        Calendar cal = Calendar.getInstance();
        int month = cal.get(Calendar.MONTH);
        int year = cal.get(Calendar.YEAR);
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(currentTime);
        if(EmptyUtils.isNotEmpty(yearSearch) && EmptyUtils.isNotEmpty(monthSearch)){
            year = Integer.parseInt(yearSearch);
            month = Integer.parseInt(monthSearch)-1;
        }
        List<String> dateList = getDayByMonth(year,month);
        //当前年月只显示到目前的日期
        if(((EmptyUtils.isEmpty(yearSearch) && EmptyUtils.isEmpty(monthSearch)) || Integer.parseInt(yearSearch) ==cal.get(Calendar.YEAR) && Integer.parseInt(monthSearch)-1 == cal.get(Calendar.MONTH))){
            List<String> tempList=new ArrayList<String>();
            tempList.addAll(dateList);
            for(int i=0;i<tempList.size();i++){
                if(!tempList.get(i).equals(dateString)){
                    dateList.remove(tempList.get(i));
                }else{
                    break;
                }
            }
        }
        int begin = pageSize*(pageNum-1);
        int end = pageSize*pageNum;
        for(int i=begin;i<dateList.size();i++){
            if(i == end){
                break;
            }
            //获取当天用户量
            WhUser whUser = new WhUser();
            whUser.setDateStr(dateList.get(i));
            int userCount=0;
            WhReport temp = new WhReport();
            userCount=whUserService.selectWhUserList(whUser).size();
            temp.setUserCount(userCount);
            temp.setReportDate(dateList.get(i));
            //获取当天vip用户量
            whUser.setLevel("834598172247461888");
            temp.setVipCount(userCount-whUserService.selectWhUserList(whUser).size());
            //开通代理数
            WhUser whUser2 = new WhUser();
            whUser2.setDateStr(dateList.get(i));
            whUser2.setUserGroup("代理用户");
            temp.setAgentCount(whUserService.selectWhUserList(whUser2).size());
            //奖励代理金额
            temp.setAgentShareCount(BigDecimal.valueOf((Math.round(whBalancerecordService.getSumMoney(dateList.get(i))*100)/100)));
            //获取未体现金额
            BigDecimal unagentSum=new BigDecimal("0.0");
            WhUserwithdraw whUserwithdraw1 = new WhUserwithdraw();
            whUserwithdraw1.setStatus("申请");
            whUserwithdraw1.setDateStr(dateList.get(i));
            for(WhUserwithdraw tempun: whUserwithdrawService.selectWhUserwithdrawList(whUserwithdraw1)){
                unagentSum = unagentSum.add(tempun.getWithdrawMoney());
            }
            temp.setUnagentShareCount(unagentSum);
            //获取当天提现总金额
            WhUserwithdraw whUserwithdraw = new WhUserwithdraw();
            whUserwithdraw.setStatus("已转账");
            whUserwithdraw.setDateStr(dateList.get(i));
            float withdrawSum = 0;
            List<WhUserwithdraw> lmWithdrawrecordList = whUserwithdrawService.selectWhUserwithdrawList(whUserwithdraw);
            for(int j=0;j<lmWithdrawrecordList.size();j++){
                withdrawSum += lmWithdrawrecordList.get(j).getWithdrawMoney().floatValue();
            }
            temp.setWithdrawSum(withdrawSum);
            //获取当天充值总金额
            WhPayrecord whPayrecord = new WhPayrecord();
            whPayrecord.setStatus("1");
            whPayrecord.setDateStr(dateList.get(i));
            float packageSum = 0;
            List<WhPayrecord> whPayrecordList = whPayrecordService.selectWhPayrecordList(whPayrecord);
            for(int k=0;k<whPayrecordList.size();k++){
                packageSum += whPayrecordList.get(k).getPayMoney().floatValue();
            }
            temp.setRechargeSum(packageSum);
            temp.setInCount(BigDecimal.valueOf(packageSum).subtract(temp.getAgentShareCount()));
            //纯收入
            /*float chunSum = packageSum -withdrawSum;
            DecimalFormat decimalFormat=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
            temp.setChunSum(Float.valueOf(decimalFormat.format(chunSum)));*/
            list.add(temp);
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(list);
        rspData.setTotal(dateList.size());
        return rspData;
    }


    /**
     * 查询汇总
     */
    @RequiresPermissions("whzj:report:list")
    @PostMapping("/getCount")
    @ResponseBody
    public AjaxResult getCount(String yearSearch, String monthSearch) throws ParseException {
        Map<String,Object> resultMap = new HashMap<>();
        //统计总充值金额
        WhPayrecord whPayrecord = new WhPayrecord();
        whPayrecord.setStatus("1");
        List<WhPayrecord> whPayrecordList = whPayrecordService.selectWhPayrecordList(whPayrecord);
        long packageSum = 0;
        if(whPayrecordList.size()>0){
            for(WhPayrecord temp:whPayrecordList){
                packageSum +=temp.getPayMoney().floatValue();
            }
        }
        resultMap.put("packageSum",packageSum);
        //统计代理账户余额
        resultMap.put("balanceSum",whUserService.getBalanceSum());
        //统计代理已提现总额
        long endWithdrawSum=0;
        WhUserwithdraw whUserwithdraw1 = new WhUserwithdraw();
        whUserwithdraw1.setStatus("已转账");
        List<WhUserwithdraw> whUserwithdrawList = whUserwithdrawService.selectWhUserwithdrawList(whUserwithdraw1);
        if(whUserwithdrawList.size()>0){
            for(WhUserwithdraw temp:whUserwithdrawList){
                endWithdrawSum +=temp.getWithdrawMoney().floatValue();
            }
        }
        resultMap.put("endWithdrawSum",endWithdrawSum);
        //统计代理兑换积分总额
        WhBalancerecord whBalancerecord1 = new WhBalancerecord();
        whBalancerecord1.setOperate("5");
        List<WhBalancerecord> whBalancerecordList1 = whBalancerecordService.selectWhBalancerecordList(whBalancerecord1);
        long exchangeSum =0;
        if(whBalancerecordList1.size()>0){
            for(WhBalancerecord temp:whBalancerecordList1){
                exchangeSum +=temp.getBalance().floatValue();
            }
        }
        resultMap.put("exchangeSum",-exchangeSum);
        //统计当月充值金额
        float rechargeSum =0;
        float withdrawSum =0;
        Calendar cal = Calendar.getInstance();
        int month = cal.get(Calendar.MONTH);
        int year = cal.get(Calendar.YEAR);
        if(EmptyUtils.isNotEmpty(yearSearch) && !"undefined".equals(yearSearch) && !"undefined".equals(monthSearch)  && EmptyUtils.isNotEmpty(monthSearch)){
            year = Integer.parseInt(yearSearch);
            month = Integer.parseInt(monthSearch)-1;
        }
        List<String> dateList = getDayByMonth(year,month);
        for(int i=0;i<dateList.size();i++){
            //获取当天提现总金额
            WhUserwithdraw whUserwithdraw = new WhUserwithdraw();
            whUserwithdraw.setStatus("已转账");
            whUserwithdraw.setDateStr(dateList.get(i));
            float dwithdrawSum = 0;
            List<WhUserwithdraw> lmWithdrawrecordList = whUserwithdrawService.selectWhUserwithdrawList(whUserwithdraw);
            for(int j=0;j<lmWithdrawrecordList.size();j++){
                dwithdrawSum += lmWithdrawrecordList.get(j).getWithdrawMoney().floatValue();
            }

            //获取当天充值总金额
            WhPayrecord whPayrecord1 = new WhPayrecord();
            whPayrecord1.setStatus("1");
            whPayrecord1.setDateStr(dateList.get(i));
            float dpackageSum = 0;
            List<WhPayrecord> whPayrecordList1 = whPayrecordService.selectWhPayrecordList(whPayrecord1);
            for(int k=0;k<whPayrecordList1.size();k++){
                dpackageSum += whPayrecordList1.get(k).getPayMoney().floatValue();
            }
            rechargeSum +=dpackageSum;
            withdrawSum +=dwithdrawSum;
        }
        //获取任务总数
        WhTask whTask = new WhTask();
        resultMap.put("taskCount",whTaskService.selectWhTaskList(whTask).size()-1);
        //获取VIP总数
        resultMap.put("vipCount",whUserService.selectWhUserByLevel().size());
        //获取用户总数
        WhUser whUser1 = new WhUser();
        resultMap.put("userCount",whUserService.selectWhUserList(whUser1).size());
        //获取代理总数
        WhUser whUser = new WhUser();
        whUser.setUserGroup("代理用户");
        resultMap.put("agentCount",whUserService.selectWhUserList(whUser).size());
        //获取代理奖励总金额
        resultMap.put("agentShareCount",whBalancerecordService.getSumMoney(""));
        //获取未发放的代理总金额
        BigDecimal unagentSum=new BigDecimal("0.0");
        BigDecimal agentSum=new BigDecimal("0.0");
        WhUserwithdraw whUserwithdraw = new WhUserwithdraw();
        whUserwithdraw.setStatus("申请");
        for(WhUserwithdraw temp: whUserwithdrawService.selectWhUserwithdrawList(whUserwithdraw)){
            unagentSum = unagentSum.add(temp.getWithdrawMoney());
        }
        resultMap.put("unagentShareCount",unagentSum);
        //获取已发放的代理总金额
        whUserwithdraw.setStatus("已转账");
        for(WhUserwithdraw temp2:whUserwithdrawService.selectWhUserwithdrawList(whUserwithdraw)){
            agentSum = agentSum.add(temp2.getWithdrawMoney());
        }
        resultMap.put("enagentShareCount",agentSum);
        resultMap.put("rechargeSum",rechargeSum);
        resultMap.put("withdrawSum",withdrawSum);
        resultMap.put("chunSum",rechargeSum-withdrawSum);
        return  new AjaxResult(AjaxResult.Type.SUCCESS,"200",resultMap);
    }

    public static List<String> getDayByMonth(int yearParam,int monthParam){
        List list = new ArrayList();
        Calendar aCalendar = Calendar.getInstance(Locale.CHINA);
        aCalendar.set(yearParam,monthParam,1);
        int year = aCalendar.get(Calendar.YEAR);//年份
        int month = aCalendar.get(Calendar.MONTH) + 1;//月份
        int day = aCalendar.getActualMaximum(Calendar.DATE);
        for (int i = 1; i <= day; i++) {
            String aDate=null;
            if(month<10&&i<10){
                aDate = String.valueOf(year)+"-0"+month+"-0"+i;
            }
            if(month<10&&i>=10){
                aDate = String.valueOf(year)+"-0"+month+"-"+i;
            }
            if(month>=10&&i<10){
                aDate = String.valueOf(year)+"-"+month+"-0"+i;
            }
            if(month>=10&&i>=10){
                aDate = String.valueOf(year)+"-"+month+"-"+i;
            }

            list.add(aDate);
        }
        //反转
        List tmpList = new ArrayList<>();
        for (int m = list.size() - 1; m >= 0; m--) {
            tmpList.add(list.get(m));
        }
        list.clear();
        list.addAll(tmpList);
        return list;
    }
}
